package study.Service.Impl;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import study.Service.MyService;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * 描述:access 权限控制
 *
 * @author Ychiha
 * @version 1.0
 * @date 13/1/2022 下午10:01
 */
@Service
public class MyServiceImpl implements MyService {

    /**
     * 权限判断
     * @param request 获取主体-URI (配判断的主题)
     * @param authentication 获取Security存储的UserDetails的信息
     * @return
     */
    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();

        if(principal instanceof UserDetails){
            UserDetails userDetails = (UserDetails) principal;
            Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();

            System.out.println("Service的集合:======>");
            //学习用 查看里面装了什么
            for(Object c : authorities){
                System.out.println(c);
            }

            //查看 允许的Uri集合 是否包含 该请求用户的Uri
            return authorities.contains(new SimpleGrantedAuthority(request.getRequestURI()));
        }

        return false;
    }
}
